<template>
  <div class="chat-container love-app">
    <div class="chat-header">
      <div style="display:flex;justify-content:space-between;align-items:center">
        <div>AI 恋爱大师</div>
        <div>聊天室 ID: {{ chatId }}</div>
      </div>
    </div>

    <div class="chat-body" ref="bodyRef">
      <div v-if="messages.length===0" class="system-note">开始新的对话，输入你的话...</div>
      <div v-for="(m, idx) in messages" :key="idx" :class="['message-row', m.role==='user' ? 'user-row' : 'ai-row']">
        <template v-if="m.role==='ai'">
          <div class="avatar ai">❤</div>
          <div class="message-bubble" v-html="m.content"></div>
        </template>
        <template v-else>
          <div class="message-bubble" v-html="m.content"></div>
          <div class="avatar user">你</div>
        </template>
      </div>
    </div>

    <div class="chat-input">
      <input v-model="input" @keydown.enter.prevent="sendMessage" class="input" placeholder="输入消息，回车发送" />
      <button class="btn" @click="clear">清空</button>
      <button class="btn primary" @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import api from '../api'

const messages = ref<{role:string, content:string}[]>([])
const input = ref('')
const chatId = ref('')
const esRef = ref<EventSource | null>(null)
const bodyRef = ref<HTMLElement | null>(null)

function genChatId(){
  return 'chat-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2,8)
}

function scrollToBottom(){
  nextTick(()=>{
    if(bodyRef.value){
      bodyRef.value.scrollTop = bodyRef.value.scrollHeight
    }
  })
}

function connectSSE(message?: string){
  const cid = chatId.value || genChatId()
  chatId.value = cid
  // Build URL with params
  const params = new URLSearchParams()
  if(message) params.append('message', message)
  params.append('chatId', cid)
  const url = api.defaults.baseURL + '/love_app/chat/sse?' + params.toString()

  // Close existing
  if(esRef.value){
    esRef.value.close()
  }

  const es = new EventSource(url)
  esRef.value = es

  es.onmessage = (e) => {
    // backend will stream pieces; append to last AI message or create new
    const data = e.data
    if(!data) return
    // If last message is AI and not terminated, append; else push new
    const last = messages.value[messages.value.length-1]
    if(last && last.role==='ai' && !last.content.endsWith('\n\n')){
      last.content += data
    } else {
      messages.value.push({role:'ai', content: data})
    }
    scrollToBottom()
  }

  es.onerror = (err)=>{
    console.error('SSE error', err)
    es.close()
    esRef.value = null
  }
}

function sendMessage(){
  const text = input.value && input.value.trim()
  if(!text) return
  messages.value.push({role:'user', content: text})
  input.value = ''
  // connect with message to start streaming
  connectSSE(text)
  scrollToBottom()
}

function clear(){
  messages.value = []
  if(esRef.value){ esRef.value.close(); esRef.value = null }
  chatId.value = ''
}

onMounted(()=>{
  chatId.value = genChatId()
})

onBeforeUnmount(()=>{
  if(esRef.value) esRef.value.close()
})
</script>

<style scoped>
.message { white-space:pre-wrap }
</style>
